package cn.xo68.boot.web.web.filter;

import cn.xo68.core.util.StringTools;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 服务相对于服务网关 前缀路径处理过滤器
 * @author wuyy<16349023@qq.com>,nnsword
 * @date 2018年3月20日下午5:37:36
 *
 */
@Order(PrefixPathHandleFilter.DEFAULT_ORDER)
@WebFilter(filterName = "prefixPathHandleFilter", urlPatterns = {"/**"})
public class PrefixPathHandleFilter implements Filter {
    /**
     * 默认Order
     */
    public static final int DEFAULT_ORDER = Integer.MAX_VALUE -100;

    //Zuul代理头信息的Key
    public static final String GATEWAY_FORWARDED_PREFIX="x-forwarded-prefix";

    public static final String ATTR_NAME="prefixPath";
    private static final String Default_Context_Path="/";

    /**
     * 返回前缀路径
     * @param request
     * @return
     */
    public static final String getPrefixPath(HttpServletRequest request){
        Object obj=  request.getAttribute(PrefixPathHandleFilter.ATTR_NAME);
        String prefixPath= StringTools.EMPTY;
        if(obj!=null){
            prefixPath=(String) obj;
        }
        return prefixPath;
    }

    /**
     * 从请求头信息中取代理路由前缀
     * @param req
     * @param otherProxyPerfix
     * @return
     */
    public static String getGatewayPrefix(HttpServletRequest req,Boolean otherProxyPerfix){
        //取zuul下发的proxy-header信息
        String prefixPath=req.getHeader(GATEWAY_FORWARDED_PREFIX);
        if(prefixPath!=null) {
            if(!otherProxyPerfix) return prefixPath;
            String path = req.getServletPath();
            int pos = path.indexOf(prefixPath);
            if (pos > 0) {
                prefixPath = path.substring(0, pos - 1) + prefixPath;
            }
            return prefixPath;
        }
        return null;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String contextPath=req.getContextPath();

        //取zuul下发的proxy-header信息
        String prefixPath= getGatewayPrefix(req,true);
        if(prefixPath!=null){
            if(!Default_Context_Path.equals(contextPath)){
                prefixPath+=contextPath;
            }
            req.setAttribute(ATTR_NAME,prefixPath);
        }else{
            prefixPath= StringTools.EMPTY;
            if(!Default_Context_Path.equals(contextPath)){
                prefixPath+=contextPath;
            }
            req.setAttribute(ATTR_NAME,prefixPath);
        }
        /*Enumeration<String> names = req.getAttributeNames();
        while (names.hasMoreElements()){
            System.out.println("Name:"+names.nextElement());
        }*/

        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }


}